package com.qf.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

@WebServlet(urlPatterns = "/code")
public class CodeServlet extends HttpServlet {

    //public static String code ;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //生成验证码
        //awt  swing-c/s 客户端
        int width =60 ;
        int height=40;

        //创建一个BufferImage对象
        BufferedImage image = new BufferedImage(60,40,BufferedImage.TYPE_INT_BGR);

        //获得图片的一个图层对象，在图层对象上绘制内容
        Graphics graphics = image.getGraphics();
        //设置颜色
        graphics.setColor(Color.pink);
        //绘制矩形
        graphics.fillRect(0,0,width,height);
        //绘制内容
        //生成验证码
        String code =createCode();

        //使用Session将生成的验证码保存起来
        req.getSession().setAttribute("code",code);
        req.getSession().setAttribute("code_create_time",System.currentTimeMillis());

        //颜色
        graphics.setColor(Color.red);

        //字体样式
        graphics.setFont(new Font("微软雅黑",Font.BOLD,20));
        //内容和位置
        graphics.drawString(code,(int)(width*0.1),(int)(height*0.8));

        //绘制10条干扰线
        graphics.setColor(Color.BLUE);
        for (int i=0;i<10;i++){
            graphics.drawLine((int)(Math.random()*width),(int)(Math.random()*height),(int)(Math.random()*width),(int)(Math.random()*height));
        }

        //将图片输出给页面Img标签
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
    private String createCode(){
       return   (int)(Math.random() * 9000+1000) + "";
    }

}
